<template>
  <div class="login_container">
    <div class="login_box">
      <!-- 头像区域 -->
      <img src="../assets/logo.png" alt="">
      <!-- 登录区域 -->
      <el-form
        class="login_form"
        :model="loginForm"
        :rules="loginFormRules"
        ref="loginFormRef">
        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input
            prefix-icon="el-icon-user-solid"
            v-model.trim="loginForm.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            prefix-icon="el-icon-lock"
            v-model.trim="loginForm.password"
            type="password"></el-input>
        </el-form-item>
        <!-- 提交按钮 -->
        <el-form-item class="btns">
          <el-button type="primary" @click="login">登录</el-button>
          <el-button type="info" @click="resetLoginForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 登录表单的数据绑定
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      // 表单验证规则
      loginFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }

        ]
      }
    }
  },
  methods: {
    // 重置方法
    resetLoginForm () {
      this.$refs.loginFormRef.resetFields()
    },
    // 登录预验证
    login () {
      this.$refs.loginFormRef.validate(async valid => {
        // 判空
        if (!valid) return
        const { data: { data, meta } } = await this.$http.post('login', this.loginForm)
        // 弹窗提示
        if (meta.status !== 200) return this.$message.error('登录失败')
        this.$message.success('登录成功')
        // 保存token
        window.sessionStorage.setItem('token', data.token)
        this.$router.push('/home')
      })
    }
  }
}
</script>

<style lang='less'  scoped>
.login_container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-color: #2b4b6b;
}
.login_box {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 450px;
  height: 300px;
  background-color: #fff;
  img {
    transform: translateY(-50%);
    height: 120px;
    width: 120px;
    border: 1px solid #eee;
    border-radius: 50%;
    user-select: none;
    -webkit-user-drag: none;
  }
}
.login_form {
  width: 100%;
  margin: -20px 0;
  padding: 0 20px;
  box-sizing: border-box;
}
.btns {
  display: flex;
  justify-content: space-around;
  .el-button--info {
    margin-left: 50px;
  }
}
</style>
